package com.zdp.oauth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdp.oauth.entity.User;
import com.zdp.oauth.entity.dto.PermissionDTO;
import com.zdp.oauth.entity.dto.RoleDTO;
import com.zdp.oauth.entity.oauth.SignInIdentity;
import com.zdp.oauth.mapper.OauthMapper;
import com.zdp.oauth.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author sesshomaru
 * @date 2022/5/23
 */
@Slf4j
@Service
public class OauthUserService implements UserDetailsService {

    private final UserMapper userMapper;

    private final OauthMapper oauthMapper;

    public OauthUserService(UserMapper userMapper,
                            OauthMapper oauthMapper) {
        this.userMapper = userMapper;
        this.oauthMapper = oauthMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) throw new RuntimeException("username param is null");
        // 1. 根据用户输入的用户名查询用户数据
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            throw new RuntimeException("user not exist");
        }
        // 2. 获取用户所拥有的权限
        List<RoleDTO> resources = oauthMapper.findOauth2RoleAndPermissionByUserId(user.getId());
        // 角色
        Set<String> roles = new HashSet<>();
        // 权限
        Set<String> permissions = new HashSet<>();
        resources.forEach(
                r -> {
                    roles.add("ROLE_" + r.getRoleCode());
                    List<PermissionDTO> permissionDTOS = r.getPermissions();
                    permissionDTOS.forEach(
                            p -> {
                                permissions.add(p.getPermissionCode());
                            }
                    );
                }
        );
        log.info("登录用户:{}, 角色:{}, 权限:{}", username, roles.toString(), permissions.toString());
        SignInIdentity signInIdentity = new SignInIdentity();
        BeanUtils.copyProperties(user, signInIdentity);

        signInIdentity.setRoles(roles);
        signInIdentity.setPermissions(permissions);

        return signInIdentity;
    }
}
